package com.gxa.service.impl.system;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxa.mapper.system.UserMapper;
import com.gxa.pojo.entity.system.User;
import com.gxa.service.system.UserService;
import com.gxa.utils.Md5Utils;
import com.gxa.utils.QueryResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author lch
 * @Date 2024/2/22 15:52
 * @Description 员工管理
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public int addUser(User user) {
        //1.检查员工工号是否正确（正则表达式）,测试=========
        if (user.getJobNumber() == null || user.getJobNumber().equals("")) {
            return -1;
        }
        //2.检查员工姓名是否正确,测试未验证=========
        if (user.getUserName() == null || user.getUserName().equals("")) {
            return -1;
        }
        //3.检查密码是否正确（正则表达式）,测试未验证=========
        if (user.getPassword() == null || user.getPassword().equals("")) {
            return -1;
        }
        //创建盐
        user.setSalt(Md5Utils.crateSalt());
        //对密码加密
        user.setPassword(Md5Utils.md5Password(user.getPassword(), user.getSalt()));
        return userMapper.insert(user);
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public Integer updateUser(User user) {
        //1.检查密码是否正确，测试未验证===============
        if (user.getPassword() != null && !user.getPassword().equals("")) {
            //创建盐
            user.setSalt(Md5Utils.crateSalt());
            //对密码加密
            user.setPassword(Md5Utils.md5Password(user.getPassword(), user.getSalt()));
        }
        return userMapper.update(user);
    }


    /**
     * 删除用户
     * @param id 用户id
     * @return
     */
    @Override
    public Integer deleteUserById(Integer id) {
        return userMapper.delete(id);
    }

    /**
     * 查询所有用户
     * @param user
     * @return
     */
    @Override
    public QueryResult queryAllUser(User user) {

        //分页查询
        Page<User> page = PageHelper.startPage(user.getPage(), user.getLimit());

        //用户数据
        List<User> userList = userMapper.query(user);

        //封装返回结果
        QueryResult queryResult = new QueryResult();
        queryResult.setData(userList);
        queryResult.setCount(page.getTotal());
        return queryResult;
    }

    /**
     * 批量删除
     * @param ids 用户id集合
     * @return
     */
    @Override
    public Integer batchDelete(List<Integer> ids) {
        return userMapper.batchDelete(ids);
    }
}
